package com.gelapps.memogel.credentials;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.gelapps.memogel.Constants;
import com.gelapps.memogel.Functions;
import com.gelapps.memogel.R;


import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;


public class CredAdd extends Activity {
	
	private String sKey;
    private EditText edTxtPass;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		if (bundle!=null)
			this.sKey = bundle.getString(Constants.getKeyString());
		else
			Log.i("CredAdd","sKey null");
        //Log.i("onCreateCard","Skey: "+this.sKey);
		setContentView(R.layout.cred_add);
        ((Button) findViewById(R.id.btnCredSave)).setOnClickListener(saveCredListener);
        ((Button) findViewById(R.id.btnCredAddNow)).setOnClickListener(btnNowCred);
        edTxtPass = (EditText) findViewById(R.id.editCredentialPass);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (preferences.getBoolean(Constants.getPrefStringShowPass(), Constants.getPrefDefaultShowPass()))
        {
            ((ImageView) findViewById(R.id.imgCredAddUser)).setVisibility(View.GONE);
            ((EditText) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_TEXT );
            ((ImageView) findViewById(R.id.imgCredAddPass)).setVisibility(View.GONE);
            edTxtPass.setInputType(InputType.TYPE_CLASS_TEXT );
        }
        ((ImageView) findViewById(R.id.imgCredAddUser)).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                if (((EditText) findViewById(R.id.editCredentialUser)).getInputType()!= InputType.TYPE_CLASS_TEXT )
                {
                    ((ImageView) findViewById(R.id.imgCredAddUser)).setImageDrawable(getResources().getDrawable(R.drawable.secure2));
                    ((EditText) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_TEXT );
                }
                else
                {
                    ((ImageView) findViewById(R.id.imgCredAddUser)).setImageDrawable(getResources().getDrawable(R.drawable.not_secure2));
                    ((EditText) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
                }
            }
        });
        ((ImageView) findViewById(R.id.imgCredAddPass)).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                if (((EditText) findViewById(R.id.editCredentialPass)).getInputType()!= InputType.TYPE_CLASS_TEXT )
                {
                    ((ImageView) findViewById(R.id.imgCredAddPass)).setImageDrawable(getResources().getDrawable(R.drawable.secure2));
                    edTxtPass.setInputType(InputType.TYPE_CLASS_TEXT );
                }
                else
                {
                    ((ImageView) findViewById(R.id.imgCredAddPass)).setImageDrawable(getResources().getDrawable(R.drawable.not_secure2));
                    edTxtPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        final Context ctx = this;
        ((Button) findViewById(R.id.btnGenPassCred)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog dialogGenPass = new Dialog(ctx);
                dialogGenPass.setContentView(R.layout.gen_pass);
                dialogGenPass.setTitle(getString(R.string.strPassTitleDialog));
                //NumberPicker np = ((NumberPicker) dialogGenPass.findViewById(R.id.npLength));  TODO
                //np.setMinValue(4);
                //np.setMaxValue(20);
                ((Button) dialogGenPass.findViewById(R.id.btnGenerate)).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        boolean num = ((CheckBox) dialogGenPass.findViewById(R.id.chboxNumber)).isChecked();
                        boolean lChar = ((CheckBox) dialogGenPass.findViewById(R.id.chboxLChar)).isChecked();
                        boolean uChar = ((CheckBox) dialogGenPass.findViewById(R.id.chboxUChar)).isChecked();
                        int length = Integer.valueOf(((EditText) dialogGenPass.findViewById(R.id.genPassLength)).getText().toString());
                        //int length = ((NumberPicker) dialogGenPass.findViewById(R.id.npLength)).getValue();
                        boolean alphaChar = ((CheckBox) dialogGenPass.findViewById(R.id.chBoxAlphaChar)).isChecked();
                        ((TextView) dialogGenPass.findViewById(R.id.txtPassGen)).setText(Functions.genPass(length, num, lChar, uChar, alphaChar));
                    }
                });

                ((Button) dialogGenPass.findViewById(R.id.btnOkGenPass)).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        edTxtPass.setText(((TextView) dialogGenPass.findViewById(R.id.txtPassGen)).getText().toString());
                        dialogGenPass.dismiss();
                    }
                });
                dialogGenPass.show();
            }
        });
	}

    private OnClickListener btnNowCred = new OnClickListener() {
        @Override
        public void onClick(View view) {
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");  //TODO
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            String currentDateandTime = sdf.format(new Date());
            ((EditText) findViewById(R.id.editCredentialDateLastUsed)).setText(currentDateandTime);
        }
    };

  /*  private OnClickListener genPassListener = new OnClickListener() {
        final Context ctx = this;
        @Override
        public void onClick(View view) {
            final Dialog dialogGenPass = new Dialog(ctx);
            dialogGenPass.setContentView(R.layout.gen_pass);
            ((Button) dialogGenPass.findViewById(R.id.btnGenerate)).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    int length = Integer.valueOf(((EditText) findViewById(R.id.editLengthPass)).getText().toString());
                    boolean num = ((CheckBox) findViewById(R.id.chboxNumber)).isChecked();
                    boolean lChar = ((CheckBox) findViewById(R.id.chboxLChar)).isChecked();
                    boolean uChar = ((CheckBox) findViewById(R.id.chboxUChar)).isChecked();
                    boolean alphaChar = ((CheckBox) findViewById(R.id.chBoxAlphaChar)).isChecked();
                    ((TextView) findViewById(R.id.txtPassGen)).setText(Functions.genPass(length, num, lChar, uChar, alphaChar));
                }
            });

            ((Button) dialogGenPass.findViewById(R.id.btnOkGenPass)).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    edTxtPass.setText(((TextView) findViewById(R.id.txtPassGen)).getText().toString());
                    dialogGenPass.dismiss();
                }
            });
            dialogGenPass.show();
        }
    };
*/
    private OnClickListener saveCredListener = new OnClickListener()
    {

		@Override
		public void onClick(View view) {
			String name = ((EditText) findViewById(R.id.editCredentialName)).getText().toString();
			String user = ((EditText) findViewById(R.id.editCredentialUser)).getText().toString();
			String password = edTxtPass.getText().toString();
			String dateCreated = ((EditText) findViewById(R.id.editCredentialDateCreated)).getText().toString();
			String dateLastUsed = ((EditText) findViewById(R.id.editCredentialDateLastUsed)).getText().toString();
			String dateExpiry = ((EditText) findViewById(R.id.editCredentialExpiry)).getText().toString();
			String site = ((EditText) findViewById(R.id.editCredentialSite)).getText().toString();
			String note = ((EditText) findViewById(R.id.editCredentialNote)).getText().toString();
            boolean test = true;
            if (!Functions.checkName(name))
            {
                test = false;
                Functions.showShortToast(getBaseContext(), getString(R.string.strCheckName));
            }
            if (!Functions.checkUser(user))
            {
                test = false;
                Functions.showShortToast(getBaseContext(), getString(R.string.strCheckUserName));
            }
            if (!Functions.checkPass(password))
            {
                test = false;
                Functions.showShortToast(getBaseContext(), getString(R.string.strCheckPassword));
            }
            if (test)
            {
			    CredentialManager.getInstance().credAdd(name, user, password, dateCreated,
                        dateLastUsed, dateExpiry, site, note, sKey);
                Functions.showLongToast(getBaseContext(),getString(R.string.strOKCreateFile));
                setResult(Constants.getResultEdit());
                finish();
            }
			/*if (writeNewFile(Constants.getPathCredentialsFile(),CredentialManager.getInstance().getStringToWrite(cTot)))
            {
                Toast.makeText(getBaseContext(), R.string.strOKCreateFile, Toast.LENGTH_LONG).show();
                Intent i = getIntent();
                setResult(Constants.getResultEdit());
                finish();
            }
			else
				Toast.makeText(getBaseContext(), R.string.strErrorCreateFile, Toast.LENGTH_LONG).show();*/
		}
    	
    };
	
	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.cred_ad, menu);
		return true;
	}*/

}
